package top.kpromise.note.config;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import top.kpromise.note.modules.user.entity.UserEntity;
import top.kpromise.note.modules.user.service.UserService;

import java.util.ArrayList;
import java.util.List;

@Component
public class CustomUserDetailsService implements UserDetailsService {

    private final UserService userService;

    public CustomUserDetailsService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        UserEntity userEntity = userService.findByUserName(userName);
        if (userEntity == null) throw new UsernameNotFoundException("userName " + userName + " not found");

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        return new User(userName, userEntity.getPassword(), true,
                true, true,
                true, grantedAuthorities);
    }
}
